//
//  OPMembersCache.m
//  OPFramework
//
//  Created by malcom on 7/17/08.
//  Copyright 2008 malcom-mac software. All rights reserved.
//

#import "OPMembersCache.h"


@implementation OPMembersCache

- (id) initForBoard:(OPBoard *) _board {
	self = [super init];
	if (self != nil) {
		obj_cacheItems = [[NSMutableDictionary alloc] init];
		_delegateBoard = [_board retain];
		p_paginatedList = [[OPPageContainer alloc] init];
		
		p_onlineUsers = nil;
		p_onlineGuests = 0;
	}
	return self;
}

- (NSString *) description {
	return [NSString stringWithFormat: @"OPMembersCache: %d users cached",[obj_cacheItems count]];
}

- (OPUser *) getUserMemberFromID:(NSNumber *) _id{
	OPUser *user = [self getUserMemberFromID: _id];
	if ([self isCacheExpired]) [user refreshCompleteProfile]; // refresh data
	return user;
}

- (OPUser *) getUserMemberFromID:(NSNumber *) _id withName:(NSString *) _username {
	OPUser *user = [obj_cacheItems objectForKey: _id];
	if (user == nil) { // not in cache, perform a sync request to get data
		user = [[OPUser alloc] initWithUsername: _username andID: _id ofBoard: _delegateBoard];
		// add to cache
		[obj_cacheItems setObject: user forKey: _id];
	}
	return user;
}

- (void) addUserMember:(OPUser *) _user {
	if (_user != nil) [obj_cacheItems setObject: _user forKey: [NSNumber numberWithInt: _user.p_userid]];
}

- (OPUser *) refreshUserCacheWithData:(NSDictionary *) _data {
	OPUser *user = [obj_cacheItems objectForKey: [NSNumber numberWithInt: [[_data objectForKey: @"poster_id"] intValue]]];
	
	if (user == nil) {
		user = [[OPUser alloc] initWithShortSummaryDataResponseFromPostLoad: _data ofBoard: _delegateBoard];
		[self addUserMember: user];
	} else {
		// refresh cache
		[user _loadShortSummaryFromData: _data];
	}
	return [user autorelease];
}

- (void) dealloc {
	[obj_cacheItems release];
	[p_onlineUsers release];
	[p_paginatedList release];
	[super dealloc];
}

- (NSArray *) getOnlineUsers {
	if ([self isCacheExpired] || p_onlineUsers == nil) {// if we want to get a new copy or we have not yet downloaded the page or the cache is expired
		[self sendXMLRequestForMethod: @"stats.getOnlineUsers"
						   withParams: nil
						parseSelector: @selector(_parseOnlineUsersList:)];
	}
	return p_onlineUsers;
}

- (void) _parseOnlineUsersList:(NSArray *) _res {
	NSDictionary *_dictVal = [_res objectAtIndex:0];
	[p_onlineUsers release]; p_onlineUsers = [[NSMutableArray alloc] init];
	p_onlineGuests = [[_dictVal objectForKey: @"guests_online"] intValue];
	
	for (NSDictionary *cUser in [_dictVal objectForKey: @"connected_users"])
		[p_onlineUsers addObject: [self getUserMemberFromID: [cUser objectForKey: @"user_id"] withName: [cUser objectForKey: @"user_name"]]];
}

- (NSArray *) getMembersListPage:(NSNumber *) _pgIdx {
	if ([_pgIdx intValue] == -1) return nil;
	// if we want to get a new copy or we have not yet downloaded the page or the cache is expired
	if ([p_paginatedList getPageAtIndex: _pgIdx] == nil || [self isCacheExpired])
		[p_paginatedList addPage: [self _loadMembersListAtPage: _pgIdx] atIndex: _pgIdx]; // ... we can perform a new request
	
	return [p_paginatedList getPageAtIndex: _pgIdx];
}

- (NSArray *) _loadMembersListAtPage:(NSNumber *) _pageIdx {
	NSArray *_params = [NSArray arrayWithObjects: _pageIdx,[NSNumber numberWithInt: 20],nil];
	[self sendXMLRequestForMethod: @"members.getMembersList" withParams:_params parseSelector: @selector(_parseMembersListPageResults:)];
	return [p_paginatedList getPageAtIndex: _pageIdx];
}

// async response
- (void)connection: (XMLRPCConnection *)connection didReceiveResponse:(XMLRPCResponse *)response forMethod: (NSString *)method {
	// super class check if it's an error, a numeric response or simply some data to parse
	if (![self _checkErrorInRawResponseFromServer: response forMethod:method]) {
		// data update to parse
		[self _parseMembersListPageResults: [NSArray arrayWithObjects: [response responseObject],method,nil]];
		// we can propagate the result to listeners
		[self dataUpdatedFor: self atMethod:method];	
	}
}

- (BOOL) _isNumericResponseFromServerAnErrorCode:(NSNumber *) _code forMethod:(NSString *) method {
	//switch ([_code intValue]) {
	
	//}
	return NO;
}

- (void) _parseMembersListPageResults:(NSArray *) _results {
	NSDictionary *resultObj = [_results objectAtIndex: 0];
	// total subscribers
	p_paginatedList.p_totalElements = [[resultObj objectForKey: @"total_users"] intValue];
	// total pages
	p_paginatedList.p_totalPages = [[resultObj objectForKey: @"total_pages"] intValue];
	
	NSMutableArray *_page = [[NSMutableArray alloc] init];
	for (NSDictionary *cUser in [resultObj objectForKey: @"users_list"]) {
		OPUser *user = [self getUserMemberFromID: [NSNumber numberWithInt: [[cUser objectForKey: @"user_id"] intValue]] 
							withName: [cUser objectForKey: @"username"]];
		[user _setAvatarImageFromFilename: [cUser objectForKey: @"user_avatar"]];

		[_page addObject: user];
	}
	[p_paginatedList addPage: [_page autorelease] atIndex: [resultObj objectForKey: @"current_page"]];
}

@end
